/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

/**
 * truncateText('ALongText', 4) => 'ALon...'
 * @param {number} limit
 * @param {string} text
 * Each Chinese character is equal to two chars
 */
export default function truncateText(text: string, n: number) {
  const exp = /[\u4E00-\u9FA5]/
  let res = ''
  let len = text.length
  const chinese = text.match(new RegExp(exp, 'g'))
  if (chinese) {
    len += chinese.length
  }
  if (len > n) {
    let i = 0
    let acc = 0
    while (true) {
      const char = text[i]
      if (exp.test(char)) {
        acc += 2
      } else {
        acc++
      }
      if (acc > n) break
      res += char
      i++
    }
    res += '...'
  } else {
    res = text
  }
  return res
}
